import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import menuData from "@/api/mock/menu-data.js";
const HtTabsComponent = () => import('@/components/common/HtTabsComponent.vue')

Vue.use(Router)

var router = new Router({
  base: process.env.BASE_URL,
  mode: 'hash',
  routes: [
    {
      path: '/401',
      name: '401',
      component: () => import('@/views/401'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/login',
      name: 'login',
      props: true,
      component: () => import('@/views/Login.vue'),
      meta: {
        single: true,
        anonymous: true
      }
    },
    {
      path: '/',
      redirect: {
        name: 'home'
      }
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/common/Home.vue'),
      meta: {
        isHome: true
      }
    },
    {
      path: '/demo',
      name: 'demo',
      component: HtTabsComponent,
      meta: {
        anonymous: true
      }
    }
  ]
})

let appMenuRoutes = menuData.getAppMenuRoutes();
appMenuRoutes.forEach(appMenuRoute=>{
  appMenuRoute.component = async (resolve) =>
      require([`@/views/${appMenuRoute.viewName}`], resolve)
  router.addRoute(appMenuRoute);
})

const ssoRedirect = () => {
  if (window.ssoConfig.mode == 'cas') {
    let service = window.location.href
    localStorage.setItem('service', service)
    window.location.href = window.ssoConfig.url + '?service=' + service
  } else if (window.ssoConfig.mode == 'oauth') {
    if (!window.ssoConfig.clientId) {
      throw 'oauth模式下必须提供clientId'
    }
    const service = window.location.href
    localStorage.setItem('service', service)
    window.location.href = `${window.ssoConfig.url}?response_type=code&client_id=${window.ssoConfig.clientId}&redirect_uri=${service}`
  }
}

// 移除url后面的指定参数
const removeUrlParams = param => {
  const query = window.location.search.substring(1)
  if (!query) {
    return
  }
  const vars = query.split('&')
  const newVars = []
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] != param) {
      newVars.push(vars[i])
    }
  }
  setTimeout(() => {
    window.history.replaceState(
      null,
      null,
      `${window.location.pathname}${
        newVars.length > 0 ? '?' : ''
      }${newVars.join('&')}`
    )
  }, 100)
}

router.beforeEach((to, from, next) => {
  // 添加路由白名单
  const routesWhiteList = [
    '/login',
    '/404',
    '/401',
    '/500',
    'tenantLogin',
    'security'
  ]
  if (
    routesWhiteList.indexOf(to.path) !== -1 ||
    routesWhiteList.indexOf(to.name) !== -1
  ) {
    next()
  } else {
    //判断是否继承上一个路由的single属性
    if (to.fullPath != from.fullPath) {
      if (to.meta && to.meta.singleInherit) {
        if (!window.opener || from.fullPath !== '/') {
          to.meta.single = from.meta.single || false
        } else {
          let href = window.opener.location.pathname
          let arr = href.split('/')
          if (arr.length > 2) {
            href = arr.slice(2).join('/')
          }
          let $router = require('./router.js').default
          let openerRoute = $router.matcher.match(href)
          if (openerRoute && openerRoute.meta) {
            to.meta.single = !!openerRoute.meta.single
          }
        }
      }
    }
    if (from.fullPath == '/' && sessionStorage.beforePath) {
      const beforePath = sessionStorage.getItem('beforePath')
      let $router = require('./router.js').default
      let historyRoute = $router.matcher.match(beforePath)
      if (historyRoute.meta && historyRoute.meta.single === true) {
        to.meta.single = !!historyRoute.meta
      }
      if (sessionStorage.beforePath.includes('/login')) {
        to.meta.single = false
      }
    }
    if (from.fullPath != '/') {
      sessionStorage.setItem('beforePath', from.fullPath)
    }

    // 1.当前为单点登录模式，且要路由到login页面，则做单点登录重定向；
    if (
      to.name == 'login' &&
      window.ssoConfig.mode &&
      window.ssoConfig.mode != 'jwt'
    ) {
      // 单点登录时如果已经携带了code或者ticket时，如果是/login路径需要跳转到默认页面（解决反复跳转的问题）
      if (
        (window.ssoConfig.mode == 'cas' || window.ssoConfig.mode == 'oauth') &&
        (to.query.code || to.query.ticket)
      ) {
        window.location.href = window.location.href.replace('/login', '')
        return
      } else {
        ssoRedirect()
      }
    }
    if (
      (to.matched.some(record => !record.meta.anonymous) &&
        !store.state.login.currentUser) ||
      (to.query && to.query.toManager == 'toManager')
    ) {
      if (to.query && to.query.toManager == 'toManager') {
        store.dispatch('login/cleanCurrentUser')
      }
      let ticket = to.query.token
      // 2.当前已经从单点页面重定向回来了，且在url地址中携带了ticket或code；
      if (window.ssoConfig.mode == 'cas') {
        ticket = to.query.ticket
      } else if (window.ssoConfig.mode == 'oauth') {
        ticket = to.query.code
      } else if (window.ssoConfig.mode == 'sso') {
        let ssoUserId = to.query.userId
        localStorage.setItem('ssoUserId', ssoUserId)
      }

      store
        // 3.携带ticket做用户鉴权；
        .dispatch('login/validAndCompletedCurrent', ticket)
        .then(() => {
          // 初始化菜单
          store.dispatch('menu/actionMenus').then(() => {})
          store.dispatch('menu/actionMenuBookmark')
          next()
          //removeUrlParams("token")
        })
        .catch(() => {
          // 4.鉴权失败时根据当前模式重定向到对应页面。
          store.dispatch('login/logoutAndCleanUp').then(() => {
            if (
              window.ssoConfig.mode &&
              window.ssoConfig.mode != 'jwt' &&
              !ticket
            ) {
              ssoRedirect()
            } else if (
              !window.ssoConfig.mode ||
              window.ssoConfig.mode == 'jwt'
            ) {
              let account = ''
              if (store.state.login.currentUser) {
                account = store.state.login.currentUser.account
              }
              next({
                path:
                  localStorage.getItem(account + 'loginRoutePath') || '/login',
                query: {
                  redirect: to.fullPath
                }
              })
            } else {
              next({path: '/500', replace: true})
            }
          })
        })
    } else {
      next()
    }
  }
})

export default router
